package cc.seiya.redis.client;

import org.aeonbits.owner.ConfigFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * @author libo
 * @date 2017/3/3 13:18
 */
public class RedisClient {

    private RedisConfig redisConfig;

    private JedisCluster jedisCluster;


    /**
     * get by key
     *
     * @param key
     * @return
     */
    public String get(String key) {
        return this.jedisCluster.get(key);
    }

    /**
     * set value  when key not exists return true ,other  return false
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setNX(String key, String value) {
        Long retVal = this.jedisCluster.setnx(key, value);
        return retVal.intValue() == 1;
    }

    /**
     * set key  to value
     *
     * @param key
     * @param value
     * @return
     */
    public String getSet(String key, String value) {
        return this.jedisCluster.getSet(key, value);
    }

    public void setex(String key,int expire,String value){
        this.jedisCluster.setex(key,expire,value);
    }

    public void expire(String key,int seconds){
        this.jedisCluster.expire(key,seconds);
    }

    /**
     * del key
     *
     * @param key
     */
    public void del(String key) {
        this.jedisCluster.del(key);
    }

    /**
     * add + 1
     *
     * @param key
     */
    public void incre(String key) {
        this.jedisCluster.incr(key);
    }

    public RedisClient() {
        redisConfig = ConfigFactory.create(RedisConfig.class);
        initRedis();
    }

    private void initRedis() {
        JedisPoolConfig jedisPool = buidlJedisPoolConfig();
        String[] hosts = redisConfig.hosts();
        Set<HostAndPort> hostAndPortSet = new HashSet<HostAndPort>(hosts.length);
        for (String host : hosts) {
            if (host == null) {
                continue;
            }
            String[] hostPortAry = host.split(":");
            if (hostPortAry == null || hostPortAry.length < 2) {
                continue;
            }
            HostAndPort hostAndPort = new HostAndPort(hostPortAry[0], Integer.valueOf(hostPortAry[1]));
            hostAndPortSet.add(hostAndPort);
        }

        jedisCluster = new JedisCluster(hostAndPortSet);
    }

    /**
     * 构建 JedisPoolConfig
     *
     * @return
     */
    private JedisPoolConfig buidlJedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisConfig.maxIdle());
        jedisPoolConfig.setMaxWaitMillis(redisConfig.maxWait());
        jedisPoolConfig.setTestOnBorrow(redisConfig.testOnBorrow());
        jedisPoolConfig.setMaxTotal(redisConfig.maxActive());
        return jedisPoolConfig;
    }

}
